package ExcelTools

import (
	"fmt"
	"net/http"
	"net/url"
	"time"

	"github.com/zeromicro/go-zero/rest/httpx"
	"property_api/internal/logic/excel/ExcelTools"
	"property_api/internal/svc"
	"property_api/internal/types"
)

func ExportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.ExportFrom
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := ExcelTools.NewExportLogic(r.Context(), svcCtx)
		resp, err := l.Export(&req)
		if err != nil {
			fmt.Println("有问题")
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			fmt.Println("无问题")
			// 设置 HTTP 响应头
			// 设置 HTTP 响应头
			w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") // Excel 文件类型

			//判断是否is_bul为1，如果为1则导出空数据，并且文件就是表明，如果为0，则是导出数据那么导出的文件名为表名加当前时间
			if req.IsBul == 0 {
				now := time.Now()
				formattedTime := now.Format("20060102")
				fileName := fmt.Sprintf("%s%s.xlsx", req.TableName, formattedTime)
				encodedFileName := url.QueryEscape(fileName)
				w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s; filename*=UTF-8''%s", encodedFileName, encodedFileName)) // 文件下载提示
			} else if req.IsBul == 1 {
				fileName := fmt.Sprintf("%s.xlsx", req.TableName)
				encodedFileName := url.QueryEscape(fileName)
				w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s; filename*=UTF-8''%s", encodedFileName, encodedFileName)) // 文件下载提示
			}
			fmt.Println("设置成功：", req.TableName)
			w.Header().Set("Content-Length", fmt.Sprintf("%d", len(resp.Data))) // 响应体长度 // 设置文件大小

			// 将二进制数据写入响应流
			w.Write(resp.Data)
		}
	}
}
